package com.example.printservice.Service.Impl;

import cn.hutool.core.util.StrUtil;
import com.aspose.pdf.internal.imaging.fileformats.cdr.objects.CdrOutline;
import com.example.printservice.Service.MyPrintService;
import com.example.printservice.constants.Constants;
import com.example.printservice.entity.DocumentConfiguration;
import com.example.printservice.utils.PageIndexUtil;
import com.example.printservice.utils.ToPDF;
import com.profesorfalken.wmi4java.WMI4Java;
import com.profesorfalken.wmi4java.WMIClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.printing.Scaling;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.print.*;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaSizeName;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.PrinterJob;
import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MyPrintServiceImpl implements MyPrintService {
    @Autowired
    ToPDF toPDF;

    @Override
    synchronized public Boolean print(@RequestBody DocumentConfiguration documentConfiguration) {
        boolean flag = false;
        String path = documentConfiguration.getFileName(); // 要遍历的路径
        PrintService printService = PrintServiceLookup.lookupDefaultPrintService(); // 获取本地打印机
        try {
            File file = new File(path);		// 获取其file对象
            File[] fs = file.listFiles();	// 遍历path下的文件和目录，放在File数组中
            for (int i = 0; i < documentConfiguration.getCount(); i++) {
                for(File f:fs){					// 遍历File[]数组
                    if(!f.isDirectory() && documentConfiguration.getPageIndex().contains(Integer.valueOf(f.getName().substring(0, f.getName().lastIndexOf("."))))) {      // 若非目录(即文件)，则打印
                        DocPrintJob job = printService.createPrintJob();
                        // 文件类型
                        DocFlavor flavor = DocFlavor.INPUT_STREAM.JPEG;
                        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
                        pras.add(MediaSizeName.ISO_A4);
                        DocAttributeSet das = new HashDocAttributeSet();
                        InputStream input = new FileInputStream(f);
                        Doc doc = new SimpleDoc(input, flavor, das);
                        job.print(doc, pras);
                        flag = true;
                    }
                }
            }
        } catch (PrintException | FileNotFoundException e) {
            flag = false;
            e.printStackTrace();
        }
//        // 载入需要打印的pdf
//        File file = new File(path);
//        PDDocument document = null;
//        PrinterJob job = null;
//        try {
//            // 加载为可操作的PDDocument对象
//            document = PDDocument.load(file);
//            // 获取可用的打印机
//            log.info("您配置了如下打印机" + Constants.PRINTER_NAMES);
//            job = getPrintServiceByName(Constants.PRINTER_NAMES);
//            job = setPageStyle(job, documentConfiguration, document);
//            job.setCopies(documentConfiguration.getCount());
//            job.print();
//            if (file.exists() && file.isFile()) {
//                document.close();
//                boolean b = file.delete();
//            }
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
        return flag;
    }

    public PrinterJob getPrintServiceByName(List<String> printerNames) throws Exception {
        log.info("可用的打印机：" + Arrays.toString(PrinterJob.lookupPrintServices()));
        PrinterJob job = PrinterJob.getPrinterJob();
        boolean flag = false;
        for (PrintService service : PrinterJob.lookupPrintServices()) {
            for (String name : printerNames) {
                if (service.getName().contains(name)) {
                    flag = true;
                    job.setPrintService(service);
                    break;
                }
            }
            if (flag) break;
        }
//        List<String> printers = getAllPrint();
//        // 遍历查询打印机名称
//        for (String name : printerNames) {
//            for (String online : printers) {
//                System.out.println("online:" + online);
//                System.out.println("name:" + name);
//                if (online.equals(name)) {
//                    for (PrintService service : PrinterJob.lookupPrintServices()) {
//                        System.out.println("service:" + service.toString());
//                        if (online.equals(service.getName())) {
//                            job.setPrintService(service);
//                            flag = true;
//                            break;
//                        }
//                    }
//                }
//                if (flag) break;
//            }
//            if (flag) break;
//        }
        if (!flag) {
            throw new RuntimeException("打印失败，未找到如下\n" + printerNames + "的打印机，请检查。");
        }
        return job;
    }


    // 设置打印格式
    public PrinterJob setPageStyle(PrinterJob job, DocumentConfiguration documentConfiguration, PDDocument document) {

        log.info("documentConfiguration:" + documentConfiguration.toString());
        // 指定页设置
//        if (!StrUtil.isBlank(documentConfiguration.getPageIndex())) {
//            document = setDocument(document, documentConfiguration);
//        }
        PDFPrintable printable = new PDFPrintable(document, Scaling.ACTUAL_SIZE);
        job.setPrintable(printable);

        // 设置纵横向
        PageFormat pageFormat = new PageFormat();
//        pageFormat.setOrientation(documentConfiguration.getOrientation());

        Book book = new Book();

        book.append(printable, pageFormat, document.getNumberOfPages());
        System.out.println(document.getNumberOfPages());
        job.setPageable(book);
        return job;
    }


    // 指定页码
    public PDDocument setDocument(PDDocument document, DocumentConfiguration documentConfiguration) {
        PDDocument result = new PDDocument();
        if (documentConfiguration.getPageIndex().equals("-1")) {
            for (int i = 0; i <= document.getNumberOfPages() / 2; i++) {
                int index = 2 * i + 1;
                if (index <= document.getNumberOfPages()) {
                    System.out.println(index);
                    result.addPage(document.getPage(index - 1));
                }
            }
        } else if (documentConfiguration.getPageIndex().equals("0")) {
            for (int i = 1; i <= document.getNumberOfPages() / 2; i++) {
                int index = 2 * i;
                if (index <= document.getNumberOfPages()) {
                    System.out.println(index);
                    result.addPage(document.getPage(index - 1));
                }
            }
        } else {
//            PageIndexUtil.getPageIndex(documentConfiguration.getPageIndex()).forEach(integer -> {
//                result.addPage(document.getPage(integer - 1));
//            });
        }
        return result;
    }

    // 获取在线的打印机
    @Override
    public List<String> getAllPrint() {
        String rawOutput = WMI4Java
                .get()
                .properties(Arrays.asList("Name", "WorkOffline"))
                .filters(Arrays.asList("$_.WorkOffline -eq 0"))
                .getRawWMIObjectOutput(WMIClass.WIN32_PRINTER);
        System.out.println(rawOutput);
        List<String> printers = Arrays.stream(rawOutput.split("(\r?\n)"))
                .filter(line -> line.startsWith("Name"))
                .map(line -> line.replaceFirst(".* : ", ""))
                .collect(Collectors.toList());
        return printers;
    }
}
